/*
 * 平面编辑器主文件
 */
import React, { Component } from 'react';
import classnames from 'classnames';
import { connect } from 'dva';
import { bindActionCreators } from 'redux';

import zoomProvider from '../../../../utils/zoomProvider';
import pathProvider from '../../../provider/pathProvider';
import Phone from './Phone';
// import Preview from './Preview';
import Widget from './Widget';
import Ruler from './Ruler';

import widgetTypes from '../../../../consts/widgetTypes';
import switchTypes from '../../../../consts/switchTypes';
import editorTypes from '../../../../consts/editorTypes';
import editorSize from '../../../../consts/editorSize';

import storage from '../../../../utils/storage';
import eventHelper from '../../../../utils/EventHelper';
import tool from '../../../../utils/tool';
import dataProvider from '../../../../utils/dataProvider';
import consts from '../../../../utils/consts';

import widgetsActions from '../../../../actions/Editor/widgets';
import editorActions from '../../../../actions/Editor/editor';

class Plane extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            transform: {
                offset_x: 0,
                offset_y: 0,
            },
        };
    }
    componentDidMount() {
        this.initElements();
        this.initContainer();
        this.bindEvent();
        this.setPaper();
    }
    setPaper() {
        const paper = Raphael(this.elements.editorPath[0], editorSize.view.width, editorSize.view.height);
        const transform = this.state.transform;
        pathProvider.setPaper(paper);
        pathProvider.setTransform(transform);
    }
    initElements() {
        this.elements = {
            canvas: $('.editor-canvas'),
            lineCanvas: $('.lineCanvas'),
            snap_theme: $('.snap_theme'),
            editor_right: $('.Editor-right'),
            editorPanel: $('.creator-editor'),
            container: $(this.refs.container),
            creator_editor: $('.creator-editor'),
            editorMainImg: $('.editor-main-img'),
            editorMainPhone: $('.editor-main-phone'),
            editorPos: $('.editor-canvas.editor_test'),
            floating_container: $('.floating_container'),
            template_content_region: $('.template-content-region'),
            template_property_content: $('.template-property-content'), // 模板AR property
            editorPath: $('.editor-path-canvas'),
        };
    }
    initContainer() {
        const _const = storage.data.CONST;
        let scrollTop = _const.view.height / 2 - 700,
            scrollLeft = _const.view.width / 2 - 700;
        const area = {
            width: parseFloat(_const.editor_width),
            height: parseFloat(_const.editor_height),
        };
        let top = scrollTop + this.elements.editorPanel.height() / 2 - area.height / 2;
        let left = scrollLeft + this.elements.editorPanel.width() / 2 - area.width / 2;
        let mainImgPosition = {
            left,
            top,
        };
        // set transform
        const transform = {
            offset_x: mainImgPosition.left + area.width / 2,
            offset_y: mainImgPosition.top + area.height / 2,
        };

        // reset canvas size
        this.elements.editorPos.css(storage.data.CONST.view);
        // reset the phone background img to center position
        this.elements.editorMainPhone.css({
            'margin-top': -94 - (765 - area.height) / 2,
            left: scrollLeft + this.elements.editorPanel.width() / 2 - area.width / 2,
            top: scrollTop + this.elements.editorPanel.height() / 2 - area.height / 2,
        });
        // scroll to the center position
        this.elements.editorPanel.scrollTop(scrollTop);
        this.elements.editorPanel.scrollLeft(scrollLeft);
        // reset main img position
        this.elements.editorMainImg.css(mainImgPosition);
        // reset line canvas position
        this.elements.lineCanvas.css(mainImgPosition);
        // reset snap_theme position
        this.elements.snap_theme.css({
            width: area.width,
            height: _const.resource_type == 0 && area.height > 757 ? '757px' : area.height,
            left: scrollLeft + this.elements.editorPanel.width() / 2 - area.width / 2,
            top: _const.resource_type == 0 && area.height > 757 ?
                scrollTop + this.elements.editorPanel.height() / 2 - 759.0 / 2 :
                scrollTop + this.elements.editorPanel.height() / 2 - area.height / 2,
        });
        // this.elements.snap_theme.draggable();

        this.setState({
            transform,
        });
    }
    handleOnContextMenu (){
        alert("handleOnContextMenu");
    }
    bindEvent() {
        const { fromTemplate, selectedWidget, selectWidgetsByIds, updateWidget } = this.props;
        let id = [],
            selecting = false;
        this.elements.canvas.off('click');
        this.elements.canvas.on('click', (ev) => {
            if (selecting) return;
            const widget = $(ev.target).closest('.btg-widget');
            const widgetId = widget.length ? (widget.attr('data-id')) : null;
            const indoc = $.contains(document.documentElement, ev.target);
            if (!indoc || !ev.target) return;
            if (ev.shiftKey || ev.ctrlKey) {
                // 多选
                const { selectedWidgetIds } = this.props;
                if (!widgetId) return;
                // 取消选择
                if ($(widget).hasClass('focus')) {
                    id = selectedWidgetIds.filter((id) => { return id !== widgetId; });
                } else {
                    id = selectedWidgetIds.concat(widgetId);
                }
                selectWidgetsByIds(id);
            } else if ($(widget).hasClass('focus')) {
                    // 取消选择
                selectWidgetsByIds([]);
            } else {
                selectWidgetsByIds([widgetId]);
            }
        });
        // 阻止方向键
        $(document).keydown((e) => {
            if (e.target.nodeName != 'INPUT' && e.target.nodeName != 'TEXTAREA') {
                e.stopPropagation();
                e.preventDefault();
                return false;
            }
        });        
        this.elements.canvas.selectable({
            filter: '.btg-widget',
            start(e) {
                id = [];
            },
            selecting(e) {
                selecting = true;
            },
            stop: (e, ui) => {
                setTimeout(() => {
                    selecting = false;
                }, 100);
                selectWidgetsByIds(id);
            },
            selected: (e, ui) => {
                const widgetId = $(ui.selected).attr('data-id');
                id = id.concat(widgetId);
                console.log(id);
            },
        });
    }
    updateWidgetPosition(e, arg1, arg2) {
        const { selectedWidget, selectedWidgetId, updateWidget } = this.props;
        const widget_id = selectedWidgetId;
        updateWidget(selectedWidget);
    }
    updateSelectedWidget(status) {
        const { selectedWidget, updateWidget } = this.props;
        if (selectedWidget) {
            updateWidget(selectedWidget);
        }
    }
    updateRulerPosition(e) {
        e.preventDefault();
        const fromTemplate = this.props.fromTemplate;
        if (fromTemplate) return false;
        let Ruler = this.refs.Ruler;
        const scale = zoomProvider.scale();
        let left = -this.elements.canvas.position().left / scale,
            top = -this.elements.canvas.position().top / scale;

        const preview = this.props.preview;
        if (preview.showPreview) {
            Ruler = this.refs.preview.refs.Ruler;
        }
        const { setState } = this.props;
        setState({ rulerLeft: left, rulerTop: top });
    }
    TemplatePropertyPosition(id) {
        let viewBox = this.elements.template_property_content,
            totalBox = this.elements.template_content_region,
            item = $(`#${id}`)[0];

        const templateProperty = this.props.parent.refs.mainEditor.refs.rightBar.refs.TemplateProperty;
        templateProperty.updateState('activeTab', 'content');// 切换至content
        if (!item) return false;
        let viewBoxHeight = viewBox.height(),
            totalBoxHeight = totalBox.height(),
            scroll = viewBox.scrollTop(),
            itemTop = $(item).position().top,
            itemHeight = $(item).height(),
            scrollTop = scroll + itemTop - viewBoxHeight / 2 + itemHeight / 2;
        viewBox.scrollTop(scrollTop);
    }
    handleOnPlayVideo(widget) {
        if (widget.type == consts.WIDGET_TYPE.VIDEO) {
            const page = storage.data.page;
            const root = this.props.root;
            widget.pause = !widget.pause;
            root.updateLocaleSelectedWidget(widget);
        }
    }
    reorderWidgets() { // widgets倒序排列
        const widgets = this.props.widgets;
        widgets.sort(tool.sortBy('sort', true, parseInt));
        return widgets;
    }
    render() {
        const { scale, widgets, preview, selectedPage: page, fromTemplate, switchType, editorType, selectedWidget, selectedWidgetIds, selectWidget, updateWidget, selectWidgetsByIds, editMode } = this.props;
        const className = switchType !== switchTypes.THREED_AR && editorType !== editorTypes.UNCHECKED ? 'visible-status' : 'hidden-status';
        const editModePath = (editMode == consts.EDIT_MODE.PATH);
        const rStyle = {
            WebkitTransformOrigin: '50% 50%',
            MozTransform: `scale(${scale})`,
            WebkitTransform: `scale(${scale})`,
            width: editorSize.view.width,
            height: editorSize.view.height,
        };
        const BoxStyle = {
            left: !fromTemplate ? '65px' : '0px',
        };

        let RulerNode = '';
        if (!fromTemplate && !preview.showPreview) {
            RulerNode = <Ruler ref="Ruler" />;
        }

        const previewNode = '';
        if (preview.showPreview) {
            // previewNode = <Preview top={centerTop} left={centerLeft} transform={this.transform} preview={preview} fromTemplate={fromTemplate} page={page} switchType={switchType} style={rStyle} ref="preview" />;
        }
        return (
          <div
            ref="container" id="moving_box"
            className={classnames('creator-panel creator-editor drop-containment editorquyu', className)}
            style={BoxStyle}
            onScroll={e => this.updateRulerPosition(e)}
          >
            <Phone switchType={switchType} showSnap="true" page={page} />
            <div
              style={rStyle}
              className="editor-canvas editor_test editor_hidden ui-selectable"
              data-editor-canvas aria-disabled="false"
            >

              <div className="snap_theme" />
              <div className="lineCanvas" />
                {
                        widgets.map((widget) => {
                            {
                                return (
                                  <Widget
                                    ref="widget" key={`${widget.id}-m`}
                                    transform={this.state.transform}
                                    widget={widget}
                                    widgets = {widgets}
                                    selectWidget={selectWidget}
                                    selectedWidgetIds={selectedWidgetIds}
                                    updateWidget={updateWidget}
                                    selectedWidget={selectedWidget}
                                    fromTemplate={fromTemplate}
                                    selectWidgetsByIds={selectWidgetsByIds}
                                    parent={this}
                                  />
                                );
                            }
                        })
                }
              {RulerNode}
            </div>
            <div className={classnames('creator-panel editor-path-canvas', { show: editModePath })} style={rStyle} />
            {previewNode}
          </div>);
    }
}

const mapStateToProps = ({ editor, widgets }) => {
    const pageId = editor.selectedPageId;
    return {
        page: editor.page,
        scale: editor.scale,
        widgets: widgets.filter(w => w.page_id === pageId && !w.delFlag),
        preview: editor.preview,
        fromTemplate: editor.status.fromTemplate,
        switchType: editor.status.switchType,
        centerTop: editor.centerTop,
        centerLeft: editor.centerLeft,
        editorType: editor.editorType,
        selectedWidgetIds: editor.selectedWidgetIds,
        editMode: editor.editMode,
    };
};
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({ ...widgetsActions, ...editorActions }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(Plane);
